package com.simple.piger.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.simple.piger.dto.resp.AddressComboRespDto;
import com.simple.piger.entity.AreaDistrict;
import com.simple.piger.mapper.AreaDistrictMapper;
import com.simple.piger.service.AreaDistrictService;
import com.simple.piger.utils.AjaxResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cglib.core.CollectionUtils;
import org.springframework.cglib.core.Transformer;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baolw
 * @since 2020-02-06
 */
@Service
public class AreaDistrictServiceImpl extends ServiceImpl<AreaDistrictMapper, AreaDistrict> implements AreaDistrictService {

    @Override
    public AjaxResult getProvinceList(String provinceCode) {
        EntityWrapper<AreaDistrict> ew = new EntityWrapper<>();
        ew.eq("level", "province");
        if (StringUtils.isNotBlank(provinceCode)) {
            ew.eq("post_code", provinceCode);
        }
        ew.orderBy("sort", false);
        List<AreaDistrict> list = this.selectList(ew);

        List<AddressComboRespDto> result = CollectionUtils.transform(list, new Transformer() {
            @Override
            public Object transform(Object o) {
                AreaDistrict areaDistrict = (AreaDistrict) o;
                AddressComboRespDto respDto = new AddressComboRespDto();
                respDto.setProvinceCode(areaDistrict.getPostCode());
                respDto.setProvinceName(areaDistrict.getName());
                return respDto;
            }
        });
        return new AjaxResult(200, "", result);
    }

    @Override
    public AjaxResult getCityList(String provinceCode) {
        EntityWrapper<AreaDistrict> ew = new EntityWrapper<>();
        ew.eq("level", "province");
        ew.eq("post_code", provinceCode);
        AreaDistrict areaDistrict = this.selectOne(ew);

        ew = new EntityWrapper<>();
        ew.eq("level", "city");
        ew.eq("parent_id", areaDistrict.getId());
        ew.orderBy("sort", false);
        List<AreaDistrict> list = this.selectList(ew);

        List<AddressComboRespDto> result = CollectionUtils.transform(list, new Transformer() {
            @Override
            public Object transform(Object o) {
                AreaDistrict areaDistrict = (AreaDistrict) o;
                AddressComboRespDto respDto = new AddressComboRespDto();
                respDto.setCityCode(areaDistrict.getId().toString());
                respDto.setCityName(areaDistrict.getName());
                respDto.setPostCode(areaDistrict.getPostCode());
                return respDto;
            }
        });
        return new AjaxResult(200, "", result);
    }
}
